package com.kreedx.article.factory.controller;

import com.kreedx.article.factory.entity.Article;
import com.kreedx.article.factory.repository.ArticleRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Controller
public class SimpleController {
    @Resource
    ArticleRepository articleRepository;

    @RequestMapping("/article")
    public void getArticle(String id, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());

        Optional<Article> article = articleRepository.findById(id);
        if (article.isPresent()) {
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(article.get().getContent().getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();
        }
    }

    @RequestMapping("/")
    public String index(Model model, String keyword,Integer page) {
        if (keyword == null) keyword = "";
        if (page == null) page = 0;
        Page<Article> articlePage = articleRepository.findByTitleLike(keyword, PageRequest.of(page, 10, Sort.by("createAt").descending()));
        model.addAttribute("articles", articlePage.getContent());
        return "index";
    }

    @RequestMapping("/article/{id}")
    public String getArticle(Model model, @PathVariable String id) throws IOException {

        Optional<Article> article = articleRepository.findById(id);
        article.ifPresent(value -> model.addAttribute("article", value));
        return "article";
    }
}
